package com.open.server;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import okhttp3.*;

import java.io.IOException;
import java.util.Comparator;
import java.util.HashSet;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author typsusan
 * <p>des</p>
 **/
public class BaiduImageRecognitionServer {

    /**
     * 这是基于百度云的图片标签识别，请替换自己的
     * 这个我到时候会进行删除哦！
     */
    public static final String API_KEY = "nbT1UFwG2UwSStl86PRpmb5Q";
    public static final String SECRET_KEY = "MbofsTHCMwWNHUpp1LuGFdvGVHTBA177";

    static final OkHttpClient HTTP_CLIENT = new OkHttpClient().newBuilder().build();


    public static String getImg(String img){
        MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
        RequestBody body = RequestBody.create(mediaType, "url="+img);
        Request request;
        try {
            request = new Request.Builder()
                    .url("https://aip.baidubce.com/rest/2.0/image-classify/v2/advanced_general?access_token=" + getAccessToken())
                    .method("POST", body)
                    .addHeader("Content-Type", "application/x-www-form-urlencoded")
                    .addHeader("Accept", "application/json")
                    .build();
            Response response = HTTP_CLIENT.newCall(request).execute();
            JSONArray jsonArray = JSONUtil.parseObj(response.body().string()).getJSONArray("result");
            if (jsonArray.size() == 0){
                return "暂无描述";
            }
            CollUtil.sort(jsonArray, Comparator.comparingInt(obj -> ((JSONObject) obj).getInt("score")));
            Set<String> stringSet = new HashSet<>();
            for (int i = 0; i < jsonArray.size(); i++) {
                if (i < 3){
                    JSONObject obj = (JSONObject)jsonArray.get(i);
                    stringSet.add(obj.getStr("keyword"));
                }else {
                    break;
                }
            }
            return String.join(" ",stringSet);
        } catch (IOException e) {
            e.printStackTrace();
            return "暂无描述";
        }
    }

    public static String getAccessToken() throws IOException {
        MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
        RequestBody body = RequestBody.create(mediaType, "grant_type=client_credentials&client_id=" + API_KEY
                + "&client_secret=" + SECRET_KEY);
        Request request = new Request.Builder()
                .url("https://aip.baidubce.com/oauth/2.0/token")
                .method("POST", body)
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .build();
        Response response = HTTP_CLIENT.newCall(request).execute();
        return new JSONObject(response.body().string()).getStr("access_token");
    }


}
